import React, { Component } from 'react';
import { toJS } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Tools, WhiteSpace, Icon, Checkbox, Button, Bubble } from 'weaver-mobile';
import { Form, RouteLayout } from 'weaver-mobile-page';

import { TitleUtil } from '../../util';
import Api from '../../apis/contacts';
import GroupSetting from './groupSetting';
const { getLabel } = Tools;

function getLocalRoute() {
  return window.location.hash.substring(1);
}

@inject('contactStore')
@inject('addContactStore')
@withRouter
@observer
export default class AddContact extends Component {

  prefixCls = 'email-contact-addContact';

  componentDidMount() {
    const { title } = this.props;
    title ? TitleUtil.setTitle(title) :
    TitleUtil.setTitle(getLabel('19956','添加联系人'))
  }

  componentWillUnmount() {
    TitleUtil.resetEmElement();
  }

  getFields = (condition) => {
    const { addContactStore: { form } } = this.props;
    const fields = [];
    if (condition && condition.items) { condition = condition.items; }
    if (Array.isArray(toJS(condition))) {
      condition.forEach((field) => {
        fields.push(<Form.Item
          key={field.domkey.join('__')}
          form={form}
          fieldConfig={field}
          onChange={form.onChange}
        />);
      });
    }
    return fields;
  }

  onGroupsChange = (id, v) => {
    const { addContactStore } = this.props;
    const { checkedGroups } = addContactStore;
    addContactStore.setState({ checkedGroups: [
      ...(v ? [...checkedGroups, id] : checkedGroups.filter(g => g !== id))
    ] });
  }

  onCancelAllGroup = () => {
    const { addContactStore } = this.props;
    addContactStore.setState({ checkedGroups: [] });
  }

  onSubmit = () => {
    const { addContactStore, contactStore, history } = this.props;
    const { form, checkedGroups, mailContact } = addContactStore;
    const { pass } = form.doValidate();
    if (pass) {
      Api.contactOperation({
        ...mailContact,
        ...form.formParams,
        groups: checkedGroups,
        operation: 'addOrUpdateContact',
      }).then(res => {
        const { api_status } = res;
        if (api_status) {
          contactStore.getContactCountList();
          contactStore.setState({
            mailContact: {                  //修改成功后刷新信息
              ...mailContact,
              mailUserName: form.formParams.mailUserName,
              mailaddress:form.formParams.mailAddress
            },
          });
          history.go(-1);
        } else {
          Bubble.error('操作失败', 1, { top: '50%' });
        }
      });
    }
  }

  render() {
    const { addContactStore, contactStore, history } = this.props;
    const { userGroups } = contactStore;
    const { conditions, extended, checkedGroups } = addContactStore;
    let baseInfo;
    let moreOptions;
    if (conditions.length) {
      baseInfo = this.getFields(conditions[0]);
      moreOptions = (<div className={`${this.prefixCls}-content-more-option`}>
        <div onClick={() => addContactStore.setState({ extended: !extended })} className={`${this.prefixCls}-content-more-option-header`}>
          <span>{extended ? getLabel('500262', '收起更多选项') : getLabel('500263','展开更多选项')}</span>
          <Icon type={extended ? 'up' : 'down'} />
        </div>
        {extended && this.getFields(conditions[1])}
      </div>);
    }
    return (
      <RouteLayout>
        <div className={`${this.prefixCls} wm-route-layout`} key="personCard">
          <div className={`${this.prefixCls}-content`}>
            {baseInfo}
            <WhiteSpace />
            <div className={`${this.prefixCls}-content-label-choise`}>
              <div className={`${this.prefixCls}-content-label-choise-header`}>
                <span>{getLabel('383553','选择分组')}</span>
                <div><Icon onClick={() => history.push(`${getLocalRoute()}/groupSetting`)} type="setting-up" /></div>
              </div>
              <ul className={`${this.prefixCls}-content-label-choise-body`}>
                {userGroups && userGroups.map(group => (
                  <li className={`${this.prefixCls}-content-label-choise-body-item`} key={group.goutId}>
                    <span>{group.groupName}</span>
                    <Checkbox checked={checkedGroups.indexOf(group.goutId) !== -1} onClick={v => this.onGroupsChange(group.goutId, v.target.checked)} />
                  </li>
                ))}
              </ul>
              <div className={`${this.prefixCls}-content-label-choise-footer`} onClick={this.onCancelAllGroup}>{getLabel('500264', '取消所有分组')}</div>
            </div>
            <WhiteSpace />
            {moreOptions}
            <WhiteSpace />
          </div>
          <div className="btn-group">
            <Button type="primary" onClick={this.onSubmit}>{getLabel('30986', '保存')}</Button>
          </div>
          <Route
            key="groupSetting"
            path="/**/addContact/groupSetting"
            component={GroupSetting}
          />
        </div>
      </RouteLayout>
    );
  }
}

